package cn.ecnu.service.impl;

import cn.ecnu.common.constant.BusinessConstant;
import cn.ecnu.common.constant.Constant;
import cn.ecnu.common.exception.RRXException;
import cn.ecnu.common.utils.JwtUtil;
import cn.ecnu.mapper.UserMapper;
import cn.ecnu.pojo.User;
import cn.ecnu.service.AccountService;
import cn.ecnu.vo.fromFront.LoginForm;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Map<String, Object> webLogin(LoginForm vo) {
        HashMap<String, Object> map = new HashMap<>();
        User user = userMapper.getUserByPhone(vo.getUserPhone());
        if (user == null) throw new RRXException(Constant.NO_USER.getMsg(), Constant.NO_USER.getCode());
        if (!StringUtils.equals(user.getUserPassword(), vo.getUserPassword()))
            throw new RRXException(Constant.LOGIN_ERROR.getMsg(), Constant.LOGIN_ERROR.getCode());
        String token = jwtUtil.sign(user.getUserId());
        map.put("token", token);
        map.put("id", user.getUserId());
        map.put("role", user.getRole());
        String key = String.format(BusinessConstant.ALIVE_KEY, user.getUserId());
        redisTemplate.opsForValue().set(key, "1");
        return map;
    }

    @Override
    public void logout(Integer userId) {
        String key = String.format(BusinessConstant.ALIVE_KEY, userId);
        redisTemplate.delete(key);
    }

    @Override
    public String getOpenId(String code) {
        String appId = "wxa303069991675721";
        String appSecret = "6e43a96100971c97f6d22ecf3947c105";
        //模板url，我们把appid、appsecret、code填进去就好了
        String url = new StringBuilder().append("https://api.weixin.qq.com/sns/jscode2session?appid=").append(appId)
                .append("&secret=").append(appSecret).append("&js_code=").append(code)
                .append("&grant_type=authorization_code").toString();
        //发送请求，返回的是JSON数据包
        String content = restTemplate.getForObject(url, String.class);
        //解析JSON，得到 openid
        String openid = (String) JSON.parseObject(content, HashMap.class).get("openid");
        return openid;
    }
}
